package cn.tedu.v2_3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


/**
 * 1.添加IP  功能
 * 2.Server  关闭通讯、代码简洁，
 */
public class Client {
    private Socket socket;

    public Client() {
        try{
            socket=new Socket("127.0.0.1",1234);

        } catch (NullPointerException e) {
            System.out.println("友情提示：IP传入出错导致连接失败");
        } catch (UnknownHostException e) {
            System.out.println("友情提示：IP传入错误");
        } catch(ConnectException e) {
            System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
        } catch(IOException e) {
            System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
        }
    }
    public void start()  {

        PrintWriter pw=null;
        try{

        InputStreamReader isr=new InputStreamReader(socket.getInputStream());
        pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);



        System.out.println("请对李佳怡说话：");
        Scanner input=new Scanner(System.in);
        String line=null;
        while (true) {
            String ip=socket.getInetAddress().getHostAddress();
            line = input.nextLine();
            pw.println(line);
            System.out.println(ip+"好的");
        }
        } catch(UnknownHostException e) {
                System.out.println("客户端/服务器编码集有问题");
        } catch(IOException e) {
                System.out.println("客户端/服务器编码集有问题");
            } finally{
        if(pw!=null)
            pw.close();
        }
        if (socket !=null&&!socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端输出失败");
            }
        }
    }


    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }



}